package com.iamalive;

import java.util.ArrayList;
import java.util.Iterator;
import com.iamalive.LocalCache.InfoDetails;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class UpdateInfoActivity extends FragmentActivity {
	
	private EditText mEditTextInfoBody;
	private Spinner mSpinnerRecipientsList;
	private Button mButtonAddRecipient;
	private Button mButtonDeleteRecipient;
	private Button mButtonUpdate;
	private Button mButtonDelete;
	private Button mButtonCancel;
	private int mArrayIndex;
	private ArrayList<String> mNewRecipientsToBeAdded;
	private ArrayList<String> mRecipientsToBeDeleted;
	private Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_info);
		
		mEditTextInfoBody = (EditText) findViewById(R.id.editTextUpdateInfoInfoText);
		mSpinnerRecipientsList = (Spinner) findViewById(R.id.spinnerUpdateInfoRecipientList);
		mButtonAddRecipient = (Button) findViewById(R.id.buttonUpdateInfoAddRecipient);
		mButtonDeleteRecipient = (Button) findViewById(R.id.buttonUpdateInfoDeleteRecipient);
		mButtonUpdate = (Button) findViewById(R.id.buttonUpdateInfoUpdate);
		mButtonDelete = (Button) findViewById(R.id.buttonUpdateInfoDelete);
		mButtonCancel = (Button) findViewById(R.id.buttonUpdateInfoCancel);
		mNewRecipientsToBeAdded = new ArrayList<String>();
		mRecipientsToBeDeleted = new ArrayList<String>();
		
		mContext = getApplicationContext();
		
		mArrayIndex = -1;
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mArrayIndex = extras.getInt("Array Index");
		}
			
		populateFieldsWithExistingValues();
		
		mButtonAddRecipient.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onAddRecipientButtonClicked();
            }
        });
		
		mButtonDeleteRecipient.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onDeleteRecipientButtonClicked();
            }
        });
		
		mButtonUpdate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onUpdateButtonClicked();
            }
        });
		
		mButtonDelete.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onDeleteButtonClicked();
            }
        });
		
		mButtonCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
		
	}

	private void populateFieldsWithExistingValues() {
		
		LocalCache localCache = LocalCache.getSingleInstance();
		InfoDetails infoDetails = localCache.mInfoList.get(mArrayIndex);
		mEditTextInfoBody.setText(infoDetails.infoBody);
		
		ArrayList<String> recipientList = new  ArrayList<String>();
		recipientList.add(0, getString(R.string.select_item_to_delete));
		recipientList.addAll(infoDetails.listOfRecipients);
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, recipientList);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinnerRecipientsList.setAdapter(dataAdapter);
	}
	
	private void onAddRecipientButtonClicked() {
        // Create custom dialog object
        final Dialog dialog = new Dialog(UpdateInfoActivity.this);
        // Include dialog.xml file
        dialog.setContentView(R.layout.dialog_add_recipient);
        // Set dialog title
        dialog.setTitle("Add Recipient");

        dialog.show();
        
        Button buttonOk;
        Button buttonCancel;
        final Spinner nameSpinner;
                
        buttonOk = (Button) dialog.findViewById(R.id.buttonAddRecipientOk);
        buttonCancel = (Button) dialog.findViewById(R.id.buttonAddRecipientCancel);
        nameSpinner = (Spinner) dialog.findViewById(R.id.spinnerAddRecipientName);

        //populate the existing recipient names spinner
        fillRecipientsSpinner(nameSpinner);
        
        buttonOk.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String name = (String) nameSpinner.getSelectedItem();
				if(name.isEmpty() == false) {
					mNewRecipientsToBeAdded.add(name);
					dialog.dismiss();
				} else {
					//TODO: show a dialog and remain there
				}
			}
		});
        
        buttonCancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});		
	}

	private void fillRecipientsSpinner(Spinner s) {
		LocalCache localCache = LocalCache.getSingleInstance();
		ArrayList<String> recipientNameList = new  ArrayList<String>();
		recipientNameList.add(0, getString(R.string.select_item_to_add));
		recipientNameList.addAll(localCache.getRecipientNameList());
		
		Utils.removeExistingStringEntries(recipientNameList, (localCache.mInfoList.get(mArrayIndex)).listOfRecipients);
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, recipientNameList);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(dataAdapter);
	}
	
//	private void removeExistingRecipientNames(ArrayList<String> recipientList, ArrayList<String> recipientsToRemove) {
//		Iterator<String> it = recipientsToRemove.iterator();
//		while (it.hasNext()) {
//			String existingName = it.next();
//			recipientList.remove(existingName);		    
//		}
//	}
	
	private void onDeleteRecipientButtonClicked() {
		String recipientName =  mSpinnerRecipientsList.getSelectedItem().toString();
		if(recipientName.equals(getString(R.string.select_item_to_delete))) {
			Utils.showToast(mContext, "Select a recipient name from the list");
			return;
		}
		
		SpinnerAdapter spinnerAdapter = mSpinnerRecipientsList.getAdapter();
		
		((ArrayAdapter) spinnerAdapter).remove(recipientName);
		((ArrayAdapter) spinnerAdapter).notifyDataSetChanged();
		
		//mSpinnerRecipientsList.removeView(v);
		mRecipientsToBeDeleted.add(recipientName);
		Utils.showToast(mContext, "The recipient " + recipientName + " has been added for deletion" );
	}
	
	private void onUpdateButtonClicked() {
		//TODO: get the info id and recipient id from the localcache and add this info using web-service
		LocalCache localCache = LocalCache.getSingleInstance();
		localCache.mInfoList.get(mArrayIndex).infoBody = mEditTextInfoBody.getText().toString().trim();
	
		Iterator<String> it1 = mNewRecipientsToBeAdded.iterator();
		while (it1.hasNext()) {
			localCache.mInfoList.get(mArrayIndex).listOfRecipients.add(it1.next());	    
		}
		
		Iterator<String> it2 = mRecipientsToBeDeleted.iterator();
		while (it2.hasNext()) {
			localCache.mInfoList.get(mArrayIndex).listOfRecipients.remove(it2.next());    
		}
		

		finish();
	}
	
	private void onDeleteButtonClicked() {
		LocalCache localCache = LocalCache.getSingleInstance();
		//TODO: get the info id from the localcache and delete this info using web service
		
		//delete from localcache too
		localCache.deleteInfo(mArrayIndex);
		finish();
	}


}
